from rest_framework import serializers
import re
from django_redis import get_redis_connection

from mall import settings
from users.utils import get_verify_url
from .models import Users
#因为有模型 而且有自动入库的方法 所以选择ModelSerializer
class RegisterCreatUserSerializer(serializers.ModelSerializer):
    #用户名，密码，确认密码，手机号，短信验证码，是否同意协议
    #ModelSerializer 是根据fileds 和model自动生成的字段
    #确认密码，短信验证码，不鞥自动生成
    password2 = serializers.CharField(label='校验密码', allow_null=False, allow_blank=False, write_only=True)
    sms_code = serializers.CharField(label='短信验证码', max_length=6, min_length=6, allow_null=False, allow_blank=False,
                                     write_only=True)
    allow = serializers.CharField(label='是否同意协议', allow_null=False, allow_blank=False, write_only=True)
    token = serializers.CharField(label='token',read_only=True)
    #只是用于序列化
    class Meta:
        model = Users
        fields = ['id','username','password','mobile','allow','password2','sms_code','token']
        #额外添加我们的选项
        extra_kwargs = {
            'id': {'read_only': True},
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }


    """
    1 字段类型验证
    2选项验证
    3单个字段验证
    4多个字段验证
    """
    #用户名，密码，确认密码，手机号，短信验证码，是否同意协议
    def validate_mobile(self, value):
        if not re.match(r'1[345789]\d{9}', value):
            raise serializers.ValidationError('手机号格式不正确')
        return value

    def validate_allow(self, value):
        # 注意,前段提交的是否同意,我们已经转换为字符串
        if value != 'true':
            raise serializers.ValidationError('您未同意协议')
        return value

    # 多字段校验, 密码是否一致, 短信是否一致
    def validate(self, attrs):

    # 比较密码
        password = attrs['password']
        password2 = attrs['password2']

        if password != password2:
            raise serializers.ValidationError('密码不一致')
        # 比较手机验证码
        # 获取用户提交的验证码
        code = attrs['sms_code']
        # 获取redis中的验证码
        redis_conn = get_redis_connection('code')
        # 获取手机号码
        mobile = attrs['mobile']
        redis_code = redis_conn.get('sms_%s' %attrs[ 'mobile'])
        if redis_code is None:
            raise serializers.ValidationError('验证码过期')

        if redis_code.decode() != code:
            raise serializers.ValidationError('验证码不正确')

        return attrs

    def create(self, validated_data):
            # 删除多余字段
            del validated_data['password2']
            del validated_data['sms_code']
            del validated_data['allow']

            user = super().create(validated_data)
            #密码是明文
            user.set_password(validated_data['password'])
            user.save()

            #注册完成之后 ，生成一个token
            #2 以下几行代码复制就行 ，坑太多
            from rest_framework_jwt.settings import api_settings
            jwt_payload_handler =api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER


            #jwt-payload_handler 的调用原理就是将user对象给 jwt，jwt会自动据获取指定的对象
            #返回给我们一个字符串
            payload = jwt_payload_handler(user)
            #我们需要对字符串进行编码
            token = jwt_encode_handler(payload)

            #user 中没有token
            user.token = token
            return user



class UserDetailSerializer(serializers.ModelSerializer):
    """
    用户详细信息序列化器
    """

    class Meta:
        model = Users
        fields = ('id', 'username', 'mobile', 'email')

class EmailSerializer(serializers.ModelSerializer):
    """
    邮箱序列化器
    """

    class Meta:
        model = Users
        fields = ('id', 'email')
        extra_kwargs = {
            'email': {
                'required': True
            }
        }




    def update(self, instance, validated_data):

        # instance --> 实例对象 user
        # validated_data -->验证之后的数据
        email = validated_data.get('email')
        instance.email = email
        instance.save()


        # 这里保存完成之后， 发送激活邮件
        from django.core.mail import send_mail
        #subject, message, from_email, recipient_list,

        #subject, 主题
        subject = '美多商城激活邮件'
        # message,  内容
        message = 'abc'
        #  from_email, 谁发送的
        from_email = settings.EMAIL_FROM
        # recipient_list, 接收列表
        recipient_list = [email]

        #这里就是要一个url，这个url对用户的id 或者 邮箱进行加密处理有一定的时效性

        verify_url = get_verify_url(instance,id,email)
        html_message =  '<p>尊敬的用户您好！</p>' \
                   '<p>感谢您使用美多商城。</p>' \
                   '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
                   '<p><a href="%s">%s<a></p>' % (email, verify_url, verify_url)

        # send_mail(subject,message,from_email,recipient_list,html_message=html_message)
        from celery_tasks.email.tasks import send_celery_email
        send_celery_email.delay(subject,message,from_email,recipient_list,html_message=html_messag)


        return instance

from .models import Address

class AddressSerializer(serializers.ModelSerializer):
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')


    def create(self, validated_data):

        # validated_data 中没有user
        validated_data['user'] = self.context['request'].user

        return Address.objects.create(**validated_data)

